


<!DOCTYPE html>
<html lang="zh-CN">
  <head><meta name="generator" content="Hexo 3.8.0">
    <title>计算属性和侦听器 — Vue.js</title>
    <meta charset="utf-8">
    <meta name="description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" hreflang="x-default" href="https://vuejs.org/v2/guide/computed.html">
    <link rel="alternate" hreflang="zh" href="computed.html">
    <link rel="alternate" hreflang="ja" href="https://jp.vuejs.org/v2/guide/computed.html">
    <link rel="alternate" hreflang="ru" href="https://ru.vuejs.org/v2/guide/computed.html">
    <link rel="alternate" hreflang="ko" href="https://kr.vuejs.org/v2/guide/computed.html">
    <link rel="alternate" hreflang="pt-BR" href="https://br.vuejs.org/v2/guide/computed.html">
    <link rel="alternate" hreflang="fr" href="https://fr.vuejs.org/v2/guide/computed.html">

    <meta property="og:type" content="article">
    <meta property="og:title" content="计算属性和侦听器 — Vue.js">
    <meta property="og:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta property="og:image" content="https://cn.vuejs.org//images/logo.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="计算属性和侦听器 — Vue.js">
    <meta name="twitter:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="twitter:image" content="https://cn.vuejs.org/images/logo.png">

    <link rel="apple-touch-icon" sizes="57x57" href="https://cn.vuejs.org/images/icons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="https://cn.vuejs.org/images/icons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="https://cn.vuejs.org/images/icons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="https://cn.vuejs.org/images/icons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="https://cn.vuejs.org/images/icons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="https://cn.vuejs.org/images/icons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="https://cn.vuejs.org/images/icons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="https://cn.vuejs.org/images/icons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="https://cn.vuejs.org/images/icons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="https://cn.vuejs.org/images/icons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="https://cn.vuejs.org/images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="https://cn.vuejs.org/images/icons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="https://cn.vuejs.org/images/icons/favicon-16x16.png">
    <meta name="msapplication-TileImage" content="/images/icons/ms-icon-144x144.png">
    <link rel="icon" href="https://cn.vuejs.org/images/logo.png" type="image/png">

    <meta name="msapplication-TileColor" content="#4fc08d">
    <meta name="theme-color" content="#4fc08d">

    <meta name="msapplication-config" content="browserconfig.xml">
    <link rel="manifest" href="https://cn.vuejs.org/manifest.json">

    <!-- <link href="https://fonts.googleapis.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com" rel="preconnect" crossorigin> -->

    <!-- <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono' rel='stylesheet' type='text/css'> -->
    <!-- <link href='//fonts.googleapis.com/css?family=Dosis:500&text=Vue.js' rel='stylesheet' type='text/css'> -->

    <link href="https://code.bdstatic.com/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- main page styles -->
    <link rel="stylesheet" href="https://cn.vuejs.org/css/page.css">

    <!-- this needs to be loaded before guide's inline scripts -->
    <script src="https://cn.vuejs.org/js/vue.js"></script>

    

    <script>
      Vue.config.productionTip = false
      window.PAGE_TYPE = "guide"
    </script>

    <!-- ga -->
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-46852172-3', 'cn.vuejs.org');
      ga('send', 'pageview');
    </script>
  </head>
  <body class="docs">
    <div id="mobile-bar">
      <a class="menu-button"></a>
      <a class="logo" href="https://cn.vuejs.org/"></a>
    </div>
    <div id="header">
  <a id="logo" href="https://cn.vuejs.org/">
    <img src="https://cn.vuejs.org/images/logo.png" alt="vue logo">
    <span>Vue.js</span>
  </a>
  <ul id="nav">
    <li>
  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input" aria-label="搜索">
  </form>
</li>
<li class="nav-dropdown-container learn">
  <a class="nav-link current">学习</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>文档</h4></li>
    <li>
      <ul>
        <li><a href="https://cn.vuejs.org/v2/guide/" class="nav-link current">教程</a></li>
        <li><a href="https://cn.vuejs.org/v2/api/" class="nav-link">API</a></li>
        <li><a href="https://cn.vuejs.org/v2/style-guide/" class="nav-link">风格指南</a></li>
        <li><a href="https://cn.vuejs.org/v2/examples/" class="nav-link">示例</a></li>
        <li><a href="https://cn.vuejs.org/v2/cookbook/" class="nav-link">Cookbook</a></li>
      </ul>
    </li>
    <li><h4>视频教程</h4></li>
    <li>
      <ul>
        <li><a href="https://www.vuemastery.com/courses/" class="nav-link" target="_blank" rel="sponsored noopener">Vue Mastery (英文)</a></li>
        <li><a href="https://vueschool.io/?friend=vuejs&utm_source=Vuejs.org&utm_medium=Link&utm_content=Navbar%20Dropdown" class="nav-link" target="_blank" rel="noopener">Vue School (英文)</a></li>
        <li><a href="https://learning.dcloud.io/" class="nav-link" target="_blank" rel="sponsored noopener">DCloud 视频教程</a></li>
      </ul>
    </li>
  </ul>
</li>

<li class="nav-dropdown-container ecosystem">
  <a class="nav-link">生态系统</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>帮助</h4></li>
    <li><ul>
      <li><a href="https://forum.vuejs.org/" class="nav-link" target="_blank" rel="noopener">论坛</a></li>
      <li><a href="https://chat.vuejs.org/" class="nav-link" target="_blank" rel="noopener">聊天室</a></li>
      <li><a href="https://events.vuejs.org/meetups/" class="nav-link" target="_blank" rel="noopener">聚会</a></li>
    </ul></li>
    <li><h4>工具</h4></li>
    <li>
      <ul>
        <li><a href="https://github.com/vuejs/vue-devtools" class="nav-link" target="_blank" rel="noopener">Devtools</a></li>
        <li><a href="https://cli.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue CLI</a></li>
        <li><a href="https://vue-loader.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Loader</a></li>
      </ul>
    </li>
    <li><h4>核心插件</h4></li>
    <li><ul>
      <li><a href="https://router.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Router</a></li>
      <li><a href="https://vuex.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vuex</a></li>
      <li><a href="https://ssr.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue 服务端渲染</a></li>
    </ul></li>
    <li><h4>信息</h4></li>
    <li><ul>
      <li><a href="https://news.vuejs.org" class="nav-link" target="_blank" rel="noopener">周刊</a></li>
      <li><a href="https://github.com/vuejs/vue/projects/6" class="nav-link" target="_blank" rel="noopener">Roadmap</a></li>
      <li><a href="https://events.vuejs.org/" class="nav-link" target="_blank" rel="noopener">活动</a></li>
      <li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank" rel="noopener">博客</a></li>
      <li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank" rel="noopener">工作</a></li>
    </ul></li>
  </ul>
</li>

<li>
  <a href="https://cn.vuejs.org/v2/guide/team.html" class="nav-link team">团队</a>
</li>
<li class="nav-dropdown-container resources">
  <a href="computed.html#" class="nav-link">资源列表</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://cn.vuejs.org/resources/partners.html" class="nav-link">合作伙伴</a></li>
    <li><a href="https://cn.vuejs.org/resources/themes.html" class="nav-link">主题</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank">Awesome Vue</a></li>
  </ul>
</li>

<!-- <li>
  <a href="/partners" class="nav-link ">Partners</a>
</li> -->
<li class="nav-dropdown-container support-vue">
  <a href="https://cn.vuejs.org/support-vuejs/" class="nav-link">支持 Vue</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://cn.vuejs.org/support-vuejs/#One-time-Donations" class="nav-link">一次性赞助</a></li>
    <li><a href="https://cn.vuejs.org/support-vuejs/#Recurring-Pledges" class="nav-link">周期性赞助</a></li>
    <li><a href="https://www.smallsticker.com/%E8%B4%B4%E7%BA%B8/vue.html" rel="noopener" class="nav-link">贴纸</a></li>
    <li><a href="https://osholic.com/?utm_source=vue&utm_medium=dropdown" rel="noopener" class="nav-link">周边</a></li>
    <li><a href="https://vue.threadless.com" target="_blank" rel="noopener" class="nav-link">T 恤商店</a></li>
  </ul>
</li>

<li class="nav-dropdown-container language">
  <a class="nav-link">多语言</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://vuejs.org/v2/guide/computed.html" class="nav-link" target="_blank" rel="noopener">English</a></li>
    <li><a href="https://jp.vuejs.org/v2/guide/computed.html" class="nav-link" target="_blank" rel="noopener">日本語</a></li>
    <li><a href="https://ru.vuejs.org/v2/guide/computed.html" class="nav-link" target="_blank" rel="noopener">Русский</a></li>
    <li><a href="https://kr.vuejs.org/v2/guide/computed.html" class="nav-link" target="_blank" rel="noopener">한국어</a></li>
    <li><a href="https://br.vuejs.org/v2/guide/computed.html" class="nav-link" target="_blank" rel="noopener">Português</a></li>
    <li><a href="https://fr.vuejs.org/v2/guide/computed.html" class="nav-link" target="_blank" rel="noopener">Français</a></li>
    <li><a href="https://vi.vuejs.org/v2/guide/computed.html" class="nav-link" target="_blank" rel="noopener">Tiếng Việt</a></li>
  </ul>
</li>

<li><a href="https://github.com/vuejs/cn.vuejs.org/" target="_blank" class="nav-link contribute">参与翻译</a></li>

  </ul>
</div>

    
      <div id="main" class="fix-sidebar">
        
          
  

<div class="sidebar">
  <div class="sidebar-inner">
    
    <div class="list">
      <div id="sidebar-sponsors-special">
  <div class="main-sponsor">
    <span>特别赞助商</span>
    <div>
    <a href="http://www.dcloud.io/?hmsr=vuejsorg&hmpl=&hmcu=&hmkw=&hmci=" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/dcloud.gif" alt>
    </a>
    </div>
    <div>
    <a href="https://youzan.github.io/vant?source=vuejsorg" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/vant.png" alt>
    </a>
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-left">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->

      
        <h2>
          
          教程
          
            <select class="version-select">
              <option value="SELF" selected>2.x</option>
              <option value="v1">1.0</option>
              <option value="012">0.12</option>
              <option value="011">0.11</option>
            </select>
          
        </h2>
        <ul class="menu-root">
  
    
    
      
        <li><h3>基础</h3></li>
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="installation.html" class="sidebar-link">安装</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="https://cn.vuejs.org/v2/guide/index.html" class="sidebar-link">介绍</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="instance.html" class="sidebar-link">Vue 实例</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="syntax.html" class="sidebar-link">模板语法</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="computed.html" class="sidebar-link current">计算属性和侦听器</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="class-and-style.html" class="sidebar-link">Class 与 Style 绑定</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="conditional.html" class="sidebar-link">条件渲染</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="list.html" class="sidebar-link">列表渲染</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="events.html" class="sidebar-link">事件处理</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="forms.html" class="sidebar-link">表单输入绑定</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="components.html" class="sidebar-link">组件基础</a>
    </li>
  
    
    
      
      
        <li><h3>深入了解组件</h3></li>
      
      
      
      
      
      
      
      
    
    <li>
      <a href="components-registration.html" class="sidebar-link">组件注册</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="components-props.html" class="sidebar-link">Prop</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="components-custom-events.html" class="sidebar-link">自定义事件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="components-slots.html" class="sidebar-link">插槽</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="components-dynamic-async.html" class="sidebar-link">动态组件 & 异步组件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="components-edge-cases.html" class="sidebar-link">处理边界情况</a>
    </li>
  
    
    
      
      
      
        <li><h3>过渡 & 动画</h3></li>
      
      
      
      
      
      
      
    
    <li>
      <a href="transitions.html" class="sidebar-link">进入/离开 & 列表过渡</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="transitioning-state.html" class="sidebar-link">状态过渡</a>
    </li>
  
    
    
      
      
      
      
        <li><h3>可复用性 & 组合</h3></li>
      
      
      
      
      
      
    
    <li>
      <a href="mixins.html" class="sidebar-link">混入</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="custom-directive.html" class="sidebar-link">自定义指令</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="render-function.html" class="sidebar-link">渲染函数 & JSX</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="plugins.html" class="sidebar-link">插件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="filters.html" class="sidebar-link">过滤器</a>
    </li>
  
    
    
      
      
      
      
      
        <li><h3>工具</h3></li>
      
      
      
      
      
    
    <li>
      <a href="single-file-components.html" class="sidebar-link">单文件组件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="unit-testing.html" class="sidebar-link">单元测试</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="typescript.html" class="sidebar-link">TypeScript 支持</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="deployment.html" class="sidebar-link">生产环境部署</a>
    </li>
  
    
    
      
      
      
      
      
      
        <li><h3>规模化</h3></li>
      
      
      
      
    
    <li>
      <a href="routing.html" class="sidebar-link">路由</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="state-management.html" class="sidebar-link">状态管理</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="ssr.html" class="sidebar-link">服务端渲染</a>
    </li>
  
    
    
      
      
      
      
      
      
      
        <li><h3>内在</h3></li>
      
      
      
    
    <li>
      <a href="reactivity.html" class="sidebar-link">深入响应式原理</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
        <li><h3>迁移</h3></li>
      
      
    
    <li>
      <a href="migration.html" class="sidebar-link">从 Vue 1.x 迁移</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="migration-vue-router.html" class="sidebar-link">从 Vue Router 0.7.x 迁移</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="migration-vuex.html" class="sidebar-link">从 Vuex 0.6.x 迁移到 1.0</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
        <li><h3>更多</h3></li>
      
    
    <li>
      <a href="comparison.html" class="sidebar-link">对比其他框架</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="join.html" class="sidebar-link">加入 Vue.js 社区</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="https://cn.vuejs.org/v2/guide/team.html" class="sidebar-link">认识团队</a>
    </li>
  
</ul>

      
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-right">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->


<div class="content guide with-sidebar computed-guide">
  
    
      
<div id="ad">
  <span style="float: right;">广告</span>
  <a href="https://time.geekbang.org/column/intro/216?code=mM%2FdqOPks0VQ7EkYGPNisoEpHDsb0ViHBXYa%2Fyg02k8%3D&utm_term=SPoster" target="_blank" rel="sponsored noopener">
    <img src="../../images/geekbang-ad.jpg">
  </a>
  <!-- <a href="https://ke.qq.com/course/392130?saleToken=992600&from=pclink" target="_blank" rel="sponsored noopener">
    <img src="/images/tencent-ad.png">
  </a> -->
  <!-- <script
    async
    type="text/javascript"
    src="//cdn.carbonads.com/carbon.js?serve=CKYIK2QU&placement=vuejsorg"
    id="_carbonads_js">
  </script> -->
</div>


    
  
  
    <h1>计算属性和侦听器</h1>
  

  <div class="ad-pagetop">
  <a href="http://www.tp-shop.cn/index.php?http_referer=vuejs" target="_blank" rel="noopener noreferrer">
    <span class="name">TPshop</span>
    <span class="description">中国免费商城系统 - 搜豹商城系统 - 免费50小时Vue视频教程</span>
    <span class="action">立即查看 &gt;</span>
  </a>
</div>


  
    <a class="dashAnchor" name="//dash_ref_计算属性/Section/%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7/0"></a><h2 id="计算属性">计算属性</h2><p>模板内的表达式非常便利，但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护。例如：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"example"</span>&gt;</span>
  &#123;&#123; message.split('').reverse().join('') &#125;&#125;
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p>在这个地方，模板不再是简单的声明式逻辑。你必须看一段时间才能意识到，这里是想要显示变量 <code>message</code> 的翻转字符串。当你想要在模板中多次引用此处的翻转字符串时，就会更加难以处理。</p>
<p>所以，对于任何复杂逻辑，你都应当使用<strong>计算属性</strong>。</p>
<h3 id="基础例子"><a href="computed.html#基础例子" class="headerlink" title="基础例子"></a>基础例子</h3><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"example"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Original message: "&#123;&#123; message &#125;&#125;"<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Computed reversed message: "&#123;&#123; reversedMessage &#125;&#125;"<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs js"><span class="hljs-keyword">var</span> vm = <span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#example'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">message</span>: <span class="hljs-string">'Hello'</span>
  &#125;,
  <span class="hljs-attr">computed</span>: &#123;
    <span class="hljs-comment">// 计算属性的 getter</span>
    reversedMessage: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
      <span class="hljs-comment">// `this` 指向 vm 实例</span>
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.message.split(<span class="hljs-string">''</span>).reverse().join(<span class="hljs-string">''</span>)
    &#125;
  &#125;
&#125;)</code></pre>
<p>结果：</p>

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
<script>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    reversedMessage: function () {
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

<p>这里我们声明了一个计算属性 <code>reversedMessage</code>。我们提供的函数将用作属性 <code>vm.reversedMessage</code> 的 getter 函数：</p>
<pre><code class="hljs js"><span class="hljs-built_in">console</span>.log(vm.reversedMessage) <span class="hljs-comment">// =&gt; 'olleH'</span>
vm.message = <span class="hljs-string">'Goodbye'</span>
<span class="hljs-built_in">console</span>.log(vm.reversedMessage) <span class="hljs-comment">// =&gt; 'eybdooG'</span></code></pre>
<p>你可以打开浏览器的控制台，自行修改例子中的 vm。<code>vm.reversedMessage</code> 的值始终取决于 <code>vm.message</code> 的值。</p>
<p>你可以像绑定普通属性一样在模板中绑定计算属性。Vue 知道 <code>vm.reversedMessage</code> 依赖于 <code>vm.message</code>，因此当 <code>vm.message</code> 发生改变时，所有依赖 <code>vm.reversedMessage</code> 的绑定也会更新。而且最妙的是我们已经以声明的方式创建了这种依赖关系：计算属性的 getter 函数是没有副作用 (side effect) 的，这使它更易于测试和理解。</p>
<h3 id="计算属性缓存-vs-方法"><a href="computed.html#计算属性缓存-vs-方法" class="headerlink" title="计算属性缓存 vs 方法"></a>计算属性缓存 vs 方法</h3><p>你可能已经注意到我们可以通过在表达式中调用方法来达到同样的效果：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Reversed message: "&#123;&#123; reversedMessage() &#125;&#125;"<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></code></pre>
<pre><code class="hljs js"><span class="hljs-comment">// 在组件中</span>
methods: &#123;
  <span class="hljs-attr">reversedMessage</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.message.split(<span class="hljs-string">''</span>).reverse().join(<span class="hljs-string">''</span>)
  &#125;
&#125;</code></pre>
<p>我们可以将同一函数定义为一个方法而不是一个计算属性。两种方式的最终结果确实是完全相同的。然而，不同的是<strong>计算属性是基于它们的响应式依赖进行缓存的</strong>。只在相关响应式依赖发生改变时它们才会重新求值。这就意味着只要 <code>message</code> 还没有发生改变，多次访问 <code>reversedMessage</code> 计算属性会立即返回之前的计算结果，而不必再次执行函数。</p>
<p>这也同样意味着下面的计算属性将不再更新，因为 <code>Date.now()</code> 不是响应式依赖：</p>
<pre><code class="hljs js">computed: &#123;
  <span class="hljs-attr">now</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Date</span>.now()
  &#125;
&#125;</code></pre>
<p>相比之下，每当触发重新渲染时，调用方法将<strong>总会</strong>再次执行函数。</p>
<p>我们为什么需要缓存？假设我们有一个性能开销比较大的计算属性 <strong>A</strong>，它需要遍历一个巨大的数组并做大量的计算。然后我们可能有其他的计算属性依赖于 <strong>A</strong> 。如果没有缓存，我们将不可避免的多次执行 <strong>A</strong> 的 getter！如果你不希望有缓存，请用方法来替代。</p>
<h3 id="计算属性-vs-侦听属性"><a href="computed.html#计算属性-vs-侦听属性" class="headerlink" title="计算属性 vs 侦听属性"></a>计算属性 vs 侦听属性</h3><p>Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动：<strong>侦听属性</strong>。当你有一些数据需要随着其它数据变动而变动时，你很容易滥用 <code>watch</code>——特别是如果你之前使用过 AngularJS。然而，通常更好的做法是使用计算属性而不是命令式的 <code>watch</code> 回调。细想一下这个例子：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo"</span>&gt;</span>&#123;&#123; fullName &#125;&#125;<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs js"><span class="hljs-keyword">var</span> vm = <span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#demo'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Foo'</span>,
    <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Bar'</span>,
    <span class="hljs-attr">fullName</span>: <span class="hljs-string">'Foo Bar'</span>
  &#125;,
  <span class="hljs-attr">watch</span>: &#123;
    <span class="hljs-attr">firstName</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">val</span>) </span>&#123;
      <span class="hljs-keyword">this</span>.fullName = val + <span class="hljs-string">' '</span> + <span class="hljs-keyword">this</span>.lastName
    &#125;,
    <span class="hljs-attr">lastName</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">val</span>) </span>&#123;
      <span class="hljs-keyword">this</span>.fullName = <span class="hljs-keyword">this</span>.firstName + <span class="hljs-string">' '</span> + val
    &#125;
  &#125;
&#125;)</code></pre>
<p>上面代码是命令式且重复的。将它与计算属性的版本进行比较：</p>
<pre><code class="hljs js"><span class="hljs-keyword">var</span> vm = <span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#demo'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Foo'</span>,
    <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Bar'</span>
  &#125;,
  <span class="hljs-attr">computed</span>: &#123;
    <span class="hljs-attr">fullName</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.firstName + <span class="hljs-string">' '</span> + <span class="hljs-keyword">this</span>.lastName
    &#125;
  &#125;
&#125;)</code></pre>
<p>好得多了，不是吗？</p>
<h3 id="计算属性的-setter"><a href="computed.html#计算属性的-setter" class="headerlink" title="计算属性的 setter"></a>计算属性的 setter</h3><p>计算属性默认只有 getter ，不过在需要时你也可以提供一个 setter ：</p>
<pre><code class="hljs js"><span class="hljs-comment">// ...</span>
computed: &#123;
  <span class="hljs-attr">fullName</span>: &#123;
    <span class="hljs-comment">// getter</span>
    get: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.firstName + <span class="hljs-string">' '</span> + <span class="hljs-keyword">this</span>.lastName
    &#125;,
    <span class="hljs-comment">// setter</span>
    set: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">newValue</span>) </span>&#123;
      <span class="hljs-keyword">var</span> names = newValue.split(<span class="hljs-string">' '</span>)
      <span class="hljs-keyword">this</span>.firstName = names[<span class="hljs-number">0</span>]
      <span class="hljs-keyword">this</span>.lastName = names[names.length - <span class="hljs-number">1</span>]
    &#125;
  &#125;
&#125;
<span class="hljs-comment">// ...</span></code></pre>
<p>现在再运行 <code>vm.fullName = &#39;John Doe&#39;</code> 时，setter 会被调用，<code>vm.firstName</code> 和 <code>vm.lastName</code> 也会相应地被更新。</p>
<a class="dashAnchor" name="//dash_ref_侦听器/Section/%E4%BE%A6%E5%90%AC%E5%99%A8/0"></a><h2 id="侦听器">侦听器</h2><p>虽然计算属性在大多数情况下更合适，但有时也需要一个自定义的侦听器。这就是为什么 Vue 通过 <code>watch</code> 选项提供了一个更通用的方法，来响应数据的变化。当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的。</p>
<p>例如：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"watch-example"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    Ask a yes/no question:
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"question"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>&#123;&#123; answer &#125;&#125;<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs html"><span class="hljs-comment">&lt;!-- 因为 AJAX 库和通用工具的生态已经相当丰富，Vue 核心代码没有重复 --&gt;</span>
<span class="hljs-comment">&lt;!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">var</span> watchExampleVM = <span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#watch-example'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">question</span>: <span class="hljs-string">''</span>,
    <span class="hljs-attr">answer</span>: <span class="hljs-string">'I cannot give you an answer until you ask a question!'</span>
  &#125;,
  <span class="hljs-attr">watch</span>: &#123;
    <span class="hljs-comment">// 如果 `question` 发生改变，这个函数就会运行</span>
    question: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">newQuestion, oldQuestion</span>) </span>&#123;
      <span class="hljs-keyword">this</span>.answer = <span class="hljs-string">'Waiting for you to stop typing...'</span>
      <span class="hljs-keyword">this</span>.debouncedGetAnswer()
    &#125;
  &#125;,
  <span class="hljs-attr">created</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-comment">// `_.debounce` 是一个通过 Lodash 限制操作频率的函数。</span>
    <span class="hljs-comment">// 在这个例子中，我们希望限制访问 yesno.wtf/api 的频率</span>
    <span class="hljs-comment">// AJAX 请求直到用户输入完毕才会发出。想要了解更多关于</span>
    <span class="hljs-comment">// `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识，</span>
    <span class="hljs-comment">// 请参考：https://lodash.com/docs#debounce</span>
    <span class="hljs-keyword">this</span>.debouncedGetAnswer = _.debounce(<span class="hljs-keyword">this</span>.getAnswer, <span class="hljs-number">500</span>)
  &#125;,
  <span class="hljs-attr">methods</span>: &#123;
    <span class="hljs-attr">getAnswer</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.question.indexOf(<span class="hljs-string">'?'</span>) === <span class="hljs-number">-1</span>) &#123;
        <span class="hljs-keyword">this</span>.answer = <span class="hljs-string">'Questions usually contain a question mark. ;-)'</span>
        <span class="hljs-keyword">return</span>
      &#125;
      <span class="hljs-keyword">this</span>.answer = <span class="hljs-string">'Thinking...'</span>
      <span class="hljs-keyword">var</span> vm = <span class="hljs-keyword">this</span>
      axios.get(<span class="hljs-string">'https://yesno.wtf/api'</span>)
        .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>&#123;
          vm.answer = _.capitalize(response.data.answer)
        &#125;)
        .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>&#123;
          vm.answer = <span class="hljs-string">'Error! Could not reach the API. '</span> + error
        &#125;)
    &#125;
  &#125;
&#125;)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre>
<p>结果：</p>

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
  el: '#watch-example',
  data: {
    question: '',
    answer: 'I cannot give you an answer until you ask a question!'
  },
  watch: {
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods: {
    getAnswer: function () {
      if (this.question.indexOf('?') === -1) {
        this.answer = 'Questions usually contain a question mark. ;-)'
        return
      }
      this.answer = 'Thinking...'
      var vm = this
      axios.get('https://yesno.wtf/api')
        .then(function (response) {
          vm.answer = _.capitalize(response.data.answer)
        })
        .catch(function (error) {
          vm.answer = 'Error! Could not reach the API. ' + error
        })
    }
  }
})
</script>

<p>在这个示例中，使用 <code>watch</code> 选项允许我们执行异步操作 (访问一个 API)，限制我们执行该操作的频率，并在我们得到最终结果前，设置中间状态。这些都是计算属性无法做到的。</p>
<p>除了 <code>watch</code> 选项之外，您还可以使用命令式的 <a href="https://cn.vuejs.org/v2/api/#vm-watch">vm.$watch API</a>。</p>

  
  
    <div class="guide-links">
      
      
        <span>← <a href="syntax.html">模板语法</a></span>
      
      
      
        <span style="float: right;"><a href="class-and-style.html">Class 与 Style 绑定</a> →</span>
      
    </div>
  
  <div class="footer">
      <script src="https://m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
<div id="bsa-native"></div>
<script>
_bsa.init('custom', 'CKYD62QM', 'placement:vuejsorg',
  {
    target: '#bsa-native',
    template: '<a class="native-box" href="computed.html##statlink##"><div class="native-sponsor">Sponsor</div><div class="native-text"><strong>##company##</strong> — ##description##</div></a>'
  }
);
</script>


    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/guide/computed.md" rel="noopener" target="_blank">
      在 GitHub 上编辑此页！
    </a>
  </div>
</div>

        
      </div>
      <script src="https://cn.vuejs.org/js/smooth-scroll.min.js"></script>
    

    <!-- main custom script for sidebars, version selects etc. -->
    <script src="https://cn.vuejs.org/js/css.escape.js"></script>
    <script src="https://cn.vuejs.org/js/common.js"></script>

    <!-- search -->
    <link href="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://cn.vuejs.org/css/search.css">
    <script src="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
    <script>
    [
      '#search-query-nav',
      '#search-query-sidebar',
      '#search-query-menu'
    ].forEach(function (selector) {
      if (!document.querySelector(selector)) return
      // search index defaults to v2
      var match = window.location.pathname.match(/^\/(v\d+)/)
      var version = match ? match[1] : 'v2'
      docsearch({
      appId: 'BH4D9OD16A',
      apiKey: '5638280abff9d207417bb03be05f0b25',
      indexName: 'vuejs_cn2',
      inputSelector: selector,
      algoliaOptions: { facetFilters: ["version:" + version] },
      autocompleteOptions: { hint: false, appendTo: 'body'}
      })
    })
    </script>
  </body>
</html>
